<template>
  <div>
    <van-row type="flex" justify="center">
      <van-image :src="require('@/assets/images/logo.png')"></van-image>
    </van-row>
    <van-cell-group inset>
      <!-- 输入账号（用户名） -->
      <van-field label="账号" placeholder="请输入账号" v-model="loginForm.name"></van-field>
      <!-- 输入密码 -->
      <van-field label="密码" placeholder="请输入密码" type="password" v-model="loginForm.password"></van-field>

      <!-- 登录按钮 -->
      <van-button type="primary" size="large" @click="handleLogin">登录</van-button>

      <!-- 注册按钮 -->
      <van-button class="goto" type="info" size="large" @click="handleRegister">如果没有账号，请立即注册</van-button>
    </van-cell-group>
  </div>
</template>

<script>
import * as UserAPI from "@/api/user.js" //导入登录接口
import {getStorageUser, setStorageToken, setStorageUser} from "@/utils/storage.js" //导入本地存储方法
export default {
  name: "login",
  data() {
    return {
      loginForm: {
        name: "dingding", //用户名，仅仅测试方便
        password: "123456",
      }
    }
  },

  //生命周期钩子函数，在组件DOM元素加载好了后被调用
  mounted() {
    //初始赋值 ，从本地存储中获取用户名
    this.loginForm.name = getStorageUser().name;
  },

  methods: {
    handleLogin() {
      if (this.loginForm.name === "" || this.loginForm.password === "") {
        this.$toast("账号或密码不能为空");
        return;
      }

      let params = this.loginForm;
      UserAPI.login(params).then(result => {
        // console.log(result);
        this.$toast({
          message: "登录成功！",
          duration: 1000
        });
        //把返回的 userId 、token 在本地保存
        setStorageToken(result.data.token); //保存Token
        let {id, name, avatar} = result.data;
        let user = {id, name, avatar};
        setStorageUser(user); //保存用户数据

        //实现路由跳转页面 看看当前路由是否指定有重定向地址 否则跳转 user
        let toPath = this.$route.params.redirect || "user";
        //延时1秒后路由跳转
        setTimeout(() => {
          this.$router.replace({
            path: toPath
          });
        }, 1000);
      }).catch((error) => {
        console.log(error);
      });
    },

    handleRegister() {
      //路由跳转到用户注册页面
      // this.$toast("注册，还没实现！");
      this.$router.push({
        name: "register"
      });
    }
  },
}
</script>

<style lang="less" scoped="scoped">
.goto {
  display: block;
  margin-top: 25px;
  text-align: center;
}
</style>
